<%@ page import="cn.edu.zut.cs.Model.User" %><%--
  Created by IntelliJ IDEA.
  User: Lenovo
  Date: 2021/6/24
  Time: 16:20
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>聊天界面</title>
    <link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/css/chat.css">
    <style>
        html,body{
            background: url(${pageContext.request.contextPath}/picture/cbg.png);
            background-size:cover;
        }
        p{
            font-size: large;
        }

        button:hover{
            background-color: #00a0f0;
            color: white;
        }
    </style>
    <jsp:include page="./include/commonfiles.jsp"/>
    <script>
        var toName;
        var username;
        var friends;
        var img;
        function showChat(name){
            document.getElementById("left").removeAttribute("hidden");
            document.getElementById("message"+name).setAttribute("hidden",true);
            toName=name;
            //清空聊天记录
            $("#content").html("");
            //显示当前聊天对象
            $("#new").html("<div style='color:#8cc7ff;'>正在和"+toName+"聊天</div>");
            //保存聊天记录
            var chatData = sessionStorage.getItem(toName);

            //记录当前聊天对象
            sessionStorage.setItem("chatTo",toName);

            if(chatData != null){
                //将聊天记录渲染到聊天区
                $("#content").html(chatData);
            }
        }

        $(function () {
            //获取好友
            $.ajax({
                url:"${pageContext.request.contextPath}/listFriends",
                async: false,
                success(data){
                    friends=data;
                },
                error(){
                    alert("error");
                }
            })
            //获取头像
            $.ajax({
                url:"${pageContext.request.contextPath}/userImg",
                async:false,
                success:function (data) {
                    img=data;
                },
                error() {
                    alert("error");
                }
            })
            //获取昵称
            $.ajax({
                url:"${pageContext.request.contextPath}/getUsername",
                async:false,
                success:function (res) {
                    username=res;
                    $("#userName").html("用户："+username+"<span style='float: right;color: green'>在线</span>");
                },
            })
            //初始化，隐藏输入框
            document.getElementById("left").setAttribute("hidden",true);
            //创建websocket对象
            var ws = new WebSocket("ws://" + location.host+"${pageContext.request.contextPath}" + "/chat");
            //绑定事件
            ws.onopen = function () {
                //建立连接后，显示在线信息
                $("#userName").html("用户："+username+"<span style='float: right;color: green'>在线</span>");
                sessionStorage.setItem("chatTo","empty");
            }

            //接受到服务端推送到消息后触发
            ws.onmessage = function (evt) {
                //获取服务端推送消息
                var  dataStr=evt.data;
                //将dataStr转换为json对象
                var res = JSON.parse(dataStr);
                //将from转换为json对象
                if(res.isSystem){
                    //系统消息
                    var names = res.message;
                    var chatTo = sessionStorage.getItem("chatTo");
                    /*                    alert("系统消息："+names+"\n"+"当前聊天对象"+chatTo+"\n消息来自于：" +Evt.fromName);*/
                    var isInList = false;
                    //用户退出广播
                    if(res.fromName==null&&chatTo!="empty"&&chatTo!=null){
                        for(var name of names){
                            if(name == chatTo){
                                isInList = true;
                                break;
                            }
                        }
                        if(!isInList){
                            $("#new").html("<div style='color:red;'>"+chatTo + "已经离线，仅显示聊天记录</div>");
                            document.getElementById("context_text").setAttribute("hidden",true);
                            document.getElementById("login_click").setAttribute("hidden",true);
                        }
                        else{
                            $("#new").html("<div style='color:#8cc7ff;'>正在和"+chatTo+"聊天</div>");
                            document.getElementById("context_text").removeAttribute("hidden");
                            document.getElementById("login_click").removeAttribute("hidden");
                        }
                    }

                    //1.好友列表展示
                    //2.系统广播的展示
                    var userListStr = "";
                    var broadcastListStr = "";
                    for(var name of names){
                        //在线列表拼接
                        if(name != username){
                            var identify = "";
                            var isfriend = false;
                            var color = "";
                            for(var i=0;i<friends.length;i++){
                                if(name == friends[i]){
                                    identify = "好友";
                                    color = "red";
                                    isfriend = true;
                                    break;
                                }
                            }
                            if(!isfriend){
                                identify = "陌生人";
                                color = "orange";
                            }
                            var msg = "message" + name;
                            userListStr += "<button id='lButton'"+"onclick=showChat(\'"+name+"\')>" +
                                "<div class='name'>"+ name +"</div>" +
                                "<div id=\"state"+name+"\" style=\"color: "+color+"\""+">"+identify+"<div hidden id=\""+msg+"\">" +
                                "</div></div>"+"</button><br>";
                            //系统消息拼接
                            broadcastListStr += "<p>"+ name +"上线了</p>";
                        }
                    }
                    //渲染列表和广播
                    $("#hylist").html(userListStr);
                    $("#xtlist").html(broadcastListStr);


                } else {
                    //不是系统消息
                    //将服务端推送的消息展示
                    var str = "<div class='admin-group'>" +
                        "<img class='admin-img' src=\""+res.fromImg+"\">" +
                        "<div class='admin-msg'>" +
                        "<pre class='admin-reply'>"+ res.message+
                        "</pre><i class='triangle-admin'>" + "</i>" +
                        "</div></div>";
                    if(toName==res.fromName){
                        $("#content").append(str);
                    }
                    //没有正在与之聊天
                    if(res.fromName!=sessionStorage.getItem("chatTo"))
                        document.getElementById("message"+res.fromName).removeAttribute("hidden");

                    var chatData = sessionStorage.getItem(res.fromName);
                    if(chatData != null){
                        str = chatData + str;
                    }
                    sessionStorage.setItem(res.fromName,str);

                    //让聊天区始终滚动到最下面
                    var chat = $("#content");
                    chat[0].scrollTop = chat[0].scrollHeight;
                }
            }

            ws.onclose = function () {
                //关闭连接，显示离线信息
                $("#userName").html("用户："+username+"<span style='float: right;color: red'>离线</span>");
            }

            $("#submit").click(function () {
                //获取输入的内容
                var data = $("#context_text").val();
                //清空输入区
                $("#context_text").val("");
                var json = {"toName":toName,"img":img,"message":data};
                //将数据展示在聊天区
                var str = "<div class='user-group'>" +
                    "<div class='user-msg'>" +
                    "<pre class='user-reply' >"+data+ "</pre>" +
                    "<i class='triangle-user'></i></div>" +
                    "<img class='user-img' src=\""+img+"\">" +
                    "</div>";
                $("#content").append(str);
                var chatData = sessionStorage.getItem(toName);
                if(chatData != null){
                    str = chatData + str;
                }
                sessionStorage.setItem(toName,str);
                //发送数据
                ws.send(JSON.stringify(json));
                //让聊天区始终滚动到最下面
                var chat = $("#content");
                chat[0].scrollTop = chat[0].scrollHeight;

            });
        })
    </script>
</head>
<body>
<jsp:include page="./include/silderbar.jsp"/>
<div id="contains">
    <!-聊天对象显示-!>
    <div id="new"></div>
    <div id="left">
        <div class="mobile-page">
            <div id="content"></div>
        </div>
        <textarea placeholder="在此输入文字..." style="font-size: large" id="context_text"></textarea>
        <div  id="login_click">
            <div id="welcome">欢迎使用聊天系统</div>
            <a href="javascript:void(0);" id="submit">发送</a>
        </div>
    </div>
    <div id="right">
        <div id="top">
            <p style="color: #00ff1b">在线用户</p>
            <div id="hylist"></div>
        </div>
        <%--        <div id="bottom">
                    <p style="color: #ff432e">系统广播</p>
                    <div id="xtlist">
                    </div>
                </div>--%>
    </div>
</div>

</body>
</html>